package com.woniuxy.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.woniuxy.entity.User;
import com.woniuxy.service.UserService;

public class CustomRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 1.通过账户找到uid,再通过uid找到角色信息
//		String uname = (String) principals.getPrimaryPrincipal();
//		// 2.查找角色
//		User user = userService.findUserAndRolesByName(uname);
//		
//		Set<String> roles = new HashSet<>();
//		for (Role role : user.getRoles()) {
//			roles.add(role.getRname());
//		}

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(null);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String uname = (String) token.getPrincipal();
		System.out.println("uname:" + uname);

		// 通过查询user
//		String pwd = new SimpleHash("MD5","111","zs,111",100).toString();
		User result = userService.getUserByName(uname);
		System.out.println(result);
		if(result==null) {
			return null;
		}

		// 返回信息，参数3是realm的名字
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(result.getUname(), result.getPwd(), getName());
		return info;
	}

}
